// import axios from 'axios';
import moment from 'moment';

const today = moment().format('YYYY-MM-DD');
const version = 'v.0.0.3';
const mark = `${today} ${version}`;

export default {
    namespaced: true,
    state: {
        MobileOS: '',
        width: 0,
        userInfo: {
            name: '',
            company: '',
            phone: '',
        },
        gameNum: 0,
        version: version,
    },
    mutations: {
        SET_MOBILE_OS: (state, MobileOS) => {
            console.log('SET_MOBILE_OS', MobileOS);
            state.MobileOS = MobileOS;
        },
        SET_APP_WIDTH: (state, width) => {
            console.log('SET_APP_WIDTH', width);
            state.width = width;
        },
        SET_USER_INFO: (state, userInfo) => {
            state.userInfo = userInfo;
        },
        SET_GAME_NUM: (state, gameNum) => {
            state.gameNum = Number(gameNum);
            localStorage.setItem(mark, gameNum);
            console.log('今日剩余答题次数：', localStorage.getItem(mark));
        },
    },
    actions: {
        handleMobileOS({ commit }) {
            const pattern = new RegExp(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
            commit('SET_MOBILE_OS', navigator.userAgent.match(pattern));
        },
        handleAppWidth({ commit }) {
            const app = document.querySelector('#app');
            const width = getStyle(app, 'width').replace('px', '');
            commit('SET_APP_WIDTH', Number(width));
        },
        handleInitGameNum({ state, commit }) {
            // 每日可答题3次,
            const gameNum = 3;
            const item = localStorage.getItem(mark);
            console.log(today);
            if (item == null) {
                commit('SET_GAME_NUM', gameNum);
            } else {
                commit('SET_GAME_NUM', item);
            }
        },
        handleUseGameNum({ state, commit }) {
            if (state.gameNum > 0) {
                commit('SET_GAME_NUM', state.gameNum - 1);
                return true;
            }
            return false;
        },
        handleAddGameNum({ state, commit }, num = 1) {
            console.log('handleAddGameNum', state.gameNum + num);
            commit('SET_GAME_NUM', state.gameNum + num);
        },
        handleSubmitData({ state }, score) {
            const formData = new FormData();
            formData.append('name', state.userInfo.name);
            formData.append('company', state.userInfo.company);
            formData.append('phone', state.userInfo.phone);
            formData.append('score', score);
            // 对接提交成绩接口
            // axios.post('score.php', formData);
        },
    },
};

function getStyle(obj, styleName) {
    if (obj.currentStyle) {
        return obj.currentStyle[styleName];
    } else {
        return getComputedStyle(obj, false)[styleName];
    }
}
